Skip to main content

Lambda Functions

Lambda functions in Python are small, anonymous functions defined by the lambda keyword. They can have any number of arguments but only one expression. The syntax is simple and intended for short functions that are convenient to use inside other functions, particularly those that require a simple function as an argument.

Basic Syntax

lambda arguments: expression

Examples

  • Single Argument: Here's how you define a function that adds 10 to its argument:

    add_ten = lambda x: x + 10
    print(add_ten(5)) # Output: 15
  • Multiple Arguments: Lambda functions can take multiple arguments:

    multiply = lambda x, y: x * y
    print(multiply(2, 3)) # Output: 6
  • No Arguments: A lambda function can also have no arguments:

    get_five = lambda: 5
    print(get_five()) # Output: 5

Use Cases

Sorting

Lambda functions are frequently used with functions like sorted() or list.sort() to define custom sorting criteria.

  • Sorting a List of Tuples by the second item:

    pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
    pairs.sort(key=lambda pair: pair[1])
    print(pairs)
  • Sorting a List of Dictionaries by a specific key:

    data = [{'name': 'John', 'age': 45}, {'name': 'Diane', 'age': 35}]
    sorted_data = sorted(data, key=lambda x: x['age'])
    print(sorted_data)

Filter

The filter() function uses a lambda function to filter items out of an iterable.

  • Filtering a List of numbers to include only even numbers:

    nums = [1, 2, 3, 4, 5, 6]
    even_nums = list(filter(lambda x: x % 2 == 0, nums))
    print(even_nums) # Output: [2, 4, 6]

Map

The map() function applies a lambda function to every item of an iterable.

  • Mapping a List of numbers to their squares:

    nums = [1, 2, 3, 4, 5]
    squared = list(map(lambda x: x ** 2, nums))
    print(squared) # Output: [1, 4, 9, 16, 25]

Limitations and Considerations

  • Readability: For complex functions, using def to define a function is preferred for the sake of clarity and readability.
  • Debugging: Debugging lambda functions can be more challenging than named functions due to their anonymous nature.
  • Single Expression: Lambda functions are limited to a single expression, which restricts their complexity and usability for larger tasks.

Lambda functions offer a concise way to perform small, one-liner functions in Python, especially useful within higher-order functions like map(), filter(), and sorted().